/* Copyright (c) 2015,2016 Lucky Byte, Inc.
 */
package com.lucky_byte.pay.jar.lualib;

import java.math.BigDecimal;

import org.luaj.vm2.LuaValue;
import org.postgresql.util.PGobject;

public class LuaHelper
{
	/**
	 * Lua 数据到 Java 对象转换
	 *
	 * @param arg Lua 参数
	 * @return Java 对象
	 */
	public static Object value2Object(LuaValue arg) {
		switch (arg.type()) {
		case LuaValue.TNIL:
			return null;
		case LuaValue.TBOOLEAN:
			return arg.toboolean();
		case LuaValue.TINT:
			return arg.toint();
		case LuaValue.TNUMBER:
			return new BigDecimal(arg.todouble());
		case LuaValue.TSTRING:
			return arg.tojstring();
		case LuaValue.TUSERDATA:
		case LuaValue.TLIGHTUSERDATA:
			return arg.touserdata();
		default:
			return arg.toString();
		}
	}

	/**
	 * 转换 Java 对象为 Lua 值
	 *
	 * @param object Java 对象
	 * @return Lua 值
	 */
	public static LuaValue object2Value(Object object) {
		if (object == null) {
			return LuaValue.NIL;
		}
		if (object instanceof Boolean) {
			boolean value = ((Boolean) object);
			return LuaValue.valueOf(value);
		}
		if (object instanceof Integer) {
			int value = ((Integer) object);
			return LuaValue.valueOf(value);
		}
		if (object instanceof Float) {
			double value = ((Float) object);
			return LuaValue.valueOf(value);
		}
		if (object instanceof Double) {
			double value = ((Double) object);
			return LuaValue.valueOf(value);
		}
		if (object instanceof BigDecimal) {
			double value = ((BigDecimal) object).doubleValue();
			return LuaValue.valueOf(value);
		}
		if (object instanceof PGobject) {
			PGobject pg_obj = (PGobject) object;
			return LuaValue.valueOf(pg_obj.getValue());
		}
		return LuaValue.valueOf(object.toString());
	}

}
